/**
 * 
 */

var ChangePassword = function(id, oldPassword, newPassword, options){
	this.id = id;
	this.newPassword = newPassword;
	this.oldPassword = oldPassword;
	this.error = options.error;
	this.success = options.success;
	this.changePassword();
};

ChangePassword.prototype._error = function(code, message){
	if(typeof this.error == 'function') {
		this.error(code, message);
	}
};

ChangePassword.prototype._success = function(data){
	if(typeof this.success == 'function') {
		this.success(data);
	}
};

ChangePassword.prototype.check = function(nextStatement){
	var self = this;
	var oldEncrypted = components.string.encryptPassword(self.oldPassword);
	Mysql.query("SELECT password,COUNT(*) as c1 FROM Account WHERE id="+Mysql.escape(self.id)+" LIMIT 1")
	.on('error', function(error){
		console.log('Mysql error: '+error);
		self._error(9999, 'Mysql error');
	})
	.on('result', function(result){
		if(result['c1'] == 0) {
			self._error(9999, 'Account not found');
			return;
		}
		if(result.password != oldEncrypted) {
			self._error(9999, 'Old password invalid');
			return;
		}
		nextStatement();
	});
};

ChangePassword.prototype.changePassword = function(){
	var self = this;
	var newEncrypted = components.string.encryptPassword(self.newPassword);
	self.check(function(){
		Mysql.query("UPDATE Account SET password="+Mysql.escape(newEncrypted)+" WHERE id="+Mysql.escape(self.id)+" LIMIT 1")
		.on('error', function(error){
			console.log('Mysql error: '+error);
			self._error(9999, 'Mysql error');
		})
		.on('result', function(result){
			self.success(result);
		});
	});
}

module.exports = ChangePassword;